import java.util.concurrent.PriorityBlockingQueue;

public class YimeTask2 {
    PriorityBlockingQueue<TimeTask> queue = new PriorityBlockingQueue<>();
    Object locker = new Object();
    public void schedule(Runnable runnable,long time){
        TimeTask task = new TimeTask(runnable,time);
        queue.put(task);
        synchronized (locker) {
            locker.notify();
        }
    }

    public YimeTask2(){
        Thread t = new Thread(()->{

            synchronized (locker){
            while(true){
                try{
                if(queue.isEmpty()){
                    locker.wait();
                }
                        TimeTask task = queue.peek();
                        long current = System.currentTimeMillis();
                        if (current >= task.gettime()) {
                            queue.poll();
                            task.run();
                        } else {
                            try {

                                locker.wait(task.gettime() - current);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                catch (InterruptedException e){
                    e.printStackTrace();
                }
            }

            }

        });
        t.start();
    }


}
